package com.kh.pajx.sop.service.school.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kh.pajx.sop.base.BaseServiceImpl;
import com.kh.pajx.sop.dao.ISchoolRelationDao;
import com.kh.pajx.sop.dao.school.IBossEcinfoDao;
import com.kh.pajx.sop.dao.school.IHsSchoolInfoDao;
import com.kh.pajx.sop.dao.sys.ISysDeptAreaDao;
import com.kh.pajx.sop.domain.BossEcinfo;
import com.kh.pajx.sop.domain.HsSchoolInfo;
import com.kh.pajx.sop.domain.HsSchoolRelation;
import com.kh.pajx.sop.domain.PageBean;
import com.kh.pajx.sop.domain.SOPCurrentUser;
import com.kh.pajx.sop.service.school.IHsSchoolInfoService;
import com.kh.pajx.sop.util.common.ChineseToEnglish;
import com.kh.pajx.sop.util.page.QueryHelper;
import com.kh.pajx.sop.util.page.QueryHelperForManyTable;
import com.kh.pajx.sop.util.security.encoder.Md5PwdEncoderUtil;
import com.kh.pajx.sop.util.sop.PropertyValidate;

/**
 * 学校信息业务逻辑接口
 * @author:	azzcsimp
 * @Createdate:	2014年7月24日 下午6:11:33
 */
@Service
@Transactional
public class HsSchoolInfoServiceImpl extends BaseServiceImpl<HsSchoolInfo> implements IHsSchoolInfoService{
	
	// ===============================注入=======================================
	
	// ===> service ===
	
	// ===> dao ===
	@Resource
	private IHsSchoolInfoDao hsSchoolInfoDao;
	
	@Resource
	private IBossEcinfoDao bossEcinfoDao;
	
	@Resource
	private ISysDeptAreaDao deptAreaDao;
	
	
	
	
	// ===============================方法=======================================
	
	
	// ==>1.IHsSchoolInfoService重载方法
	
	public void findSchoolListByUser(HsSchoolInfo model,String deptCode, SOPCurrentUser currentUser, int pageNum, int numPerPage) throws Exception{
		if(!currentUser.isLookAll() && (currentUser.getSclIdList()==null || currentUser.getSclIdList().size()<=0)){
			// 用户没有学校信息
			throw new Exception("您尚未绑定学校或无权限访问学校信息！");
		} 
		
		// 校验参数
		if(!validateParam(model,deptCode)){
			// 非法参数入侵
			throw new Exception("系统检测到非法参数入侵！");
		}
		
		List<String> areaCodeList = new ArrayList<String>();
		if(StringUtils.isNotEmpty(deptCode)){
			// 获取当前部门下的区域信息集合
			areaCodeList = deptAreaDao.getAreaCodeByDeptCode(deptCode);
		}
		
		QueryHelper helper = new QueryHelper(HsSchoolInfo.class, "scl");
		// 学校名称
		helper.addCondition(StringUtils.isNotEmpty(model.getSclName()), "sclName like ?","%"+PropertyValidate.encodeForSql(model.getSclName())+"%");
		// 学校编码
		helper.addCondition(StringUtils.isNotEmpty(model.getSclNumber()), "sclNumber=?", model.getSclNumber());
		// 市区编码
		helper.addCondition(StringUtils.isNotEmpty(model.getAreaCode()), "areaCode=?",model.getAreaCode());
		// 县区编码
		helper.addCondition(StringUtils.isNotEmpty(model.getCountyCode()), "countyCode=?", model.getCountyCode());
		// 审核状态
		helper.addCondition(StringUtils.isNotEmpty(model.getCheckStatusFlag()), "checkStatusFlag=?", model.getCheckStatusFlag());
		// 结算方式
		helper.addCondition(StringUtils.isNotEmpty(model.getBalanceTypeFlag()), "balanceTypeFlag = ?", model.getBalanceTypeFlag());
		// 市场人员
		helper.addCondition(StringUtils.isNotEmpty(model.getSaleUserId()), "(saleUserId=? or saleKeepId=?)", model.getSaleUserId(),model.getSaleUserId());
		// 状态标识
		helper.addCondition("sclStatusFlag=?", "1");
		// 部门信息
		helper.addConditionWithIn(StringUtils.isNotEmpty(deptCode)&&areaCodeList.size()>0, "areaCode", "areaCodeList", areaCodeList);
		// 学校列表
		helper.addConditionWithIn(!currentUser.isLookAll(),"sclId", "sclIdList", currentUser.getSclIdList());
		helper.preparePageBean(hsSchoolInfoDao, pageNum, numPerPage);
		
	}
		
	
	// ==>2.IBaseService重载方法
	
	
	private boolean validateParam(HsSchoolInfo scl,String deptCode){
		// 校验学校名称
		if(StringUtils.isNotEmpty(scl.getSclName())){
			if(!PropertyValidate.validateStrByLength(scl.getSclName(),80)){
				return false;
			}
		}
		
		// 校验学校编码
		if(StringUtils.isNotEmpty(scl.getSclNumber())){
			if(!PropertyValidate.validateSclNo(scl.getSclNumber())){
				return false;
			}
		}
		
		// 校验市区编码
		if(StringUtils.isNotEmpty(scl.getAreaCode())){
			if(!PropertyValidate.validateAreaCode(scl.getAreaCode())){
				return false;
			}
		}
		
		// 校验县区编码
		if(StringUtils.isNotEmpty(scl.getCountyCode())){
			if(!PropertyValidate.validateCountyCode(scl.getCountyCode())){
				return false;
			}
		}
		
		// 校验部门编码
		if(StringUtils.isNotEmpty(deptCode)){
			if(!PropertyValidate.validateNumberCode(deptCode, 4)){
				return false;
			}
		}
		
		// 校验市场人员
		if(StringUtils.isNotEmpty(scl.getSaleUserId())){
			if(!PropertyValidate.validateUUID(scl.getSaleUserId())){
				return false;
			}
		}
		
		// 校验结算方式
		if(StringUtils.isNotEmpty(scl.getBalanceTypeFlag())){
			if(!PropertyValidate.validateNumberCode(scl.getBalanceTypeFlag(), 1)){
				return false;
			}
		}
		
		// 校验审核状态
		if(StringUtils.isNotEmpty(scl.getCheckStatusFlag())){
			if(!PropertyValidate.validateNumberCode(scl.getCheckStatusFlag(), 1)){
				return false;
			}
		}
		
		return true;
	}
	
	
	
	
	
	
	
	// =========================以下为需要整理或废弃方法===================================	

	
	
	@Resource
	private ISchoolRelationDao hsSchoolRelationDao;
	
	
	
	@Override
	public List<HsSchoolInfo> findAll() {
		return hsSchoolInfoDao.findAll();
	}
	
	@Override
	public void save(HsSchoolInfo schoolInfo) {
		schoolInfo.setdKeyA(Md5PwdEncoderUtil.cardEncrytion(schoolInfo.getSclNumber())); // 数据区A密码
		schoolInfo.setdKeyB(Md5PwdEncoderUtil.cardEncrytion(schoolInfo.getdKeyA())); // 数据区B密码    
		schoolInfo.setbKeyA(Md5PwdEncoderUtil.cardEncrytion(schoolInfo.getdKeyB())); // 空白区A密码   
		schoolInfo.setbKeyB(Md5PwdEncoderUtil.cardEncrytion(schoolInfo.getbKeyA())); // 空白区B密码
		hsSchoolInfoDao.save(schoolInfo);
		
	}
	
	@Override
	public void save(HsSchoolInfo schoolInfo, HsSchoolRelation schoolRelation){
		schoolInfo.setdKeyA(Md5PwdEncoderUtil.cardEncrytion(schoolInfo.getSclNumber())); // 数据区A密码
		schoolInfo.setdKeyB(Md5PwdEncoderUtil.cardEncrytion(schoolInfo.getdKeyA())); // 数据区B密码    
		schoolInfo.setbKeyA(Md5PwdEncoderUtil.cardEncrytion(schoolInfo.getdKeyB())); // 空白区A密码   
		schoolInfo.setbKeyB(Md5PwdEncoderUtil.cardEncrytion(schoolInfo.getbKeyA())); // 空白区B密码
		hsSchoolInfoDao.save(schoolInfo);
		schoolRelation.setSclId(schoolInfo.getSclId());
		hsSchoolRelationDao.save(schoolRelation);
	}
	
	@Override
	public void update(HsSchoolInfo schoolInfo, HsSchoolRelation schoolRelation) {
		HsSchoolRelation lastRelation =  hsSchoolRelationDao.getSchoolRelationBySclid(schoolInfo.getSclId());
		if(!lastRelation.getBalanceTypeFlag().equals(schoolRelation.getBalanceTypeFlag())||!lastRelation.getMarketingTypeFlag().equals(schoolRelation.getMarketingTypeFlag())){
			schoolInfo.setCheckStatusFlag("0");
		}
		lastRelation.setRelationStatusFlag("0");
		hsSchoolRelationDao.update(lastRelation);
		hsSchoolInfoDao.update(schoolInfo);
		schoolRelation.setSclId(schoolInfo.getSclId());
		hsSchoolRelationDao.save(schoolRelation);
	}
	
	@Override
	public void update(HsSchoolInfo demo) {
		hsSchoolInfoDao.update(demo);
	}
	
	@Override
	public void delete(String id) {
		hsSchoolInfoDao.delete(id);
	}
	
	@Override
	public HsSchoolInfo getById(String uuid) {
		return hsSchoolInfoDao.getById(uuid);
	}
	
	@Override
	public PageBean getPageBean(int pageNum, int pageSize,
			QueryHelper queryHelper) {
		return hsSchoolInfoDao.getPageBean(pageNum, pageSize, queryHelper);
	}
	
	@Override
	public PageBean getPageBean(int pageNum, int pageSize,
			QueryHelperForManyTable queryHelper) {
		return hsSchoolInfoDao.getPageBean(pageNum, pageSize, queryHelper);
	}
	
	/**
	 * @see com.kh.pajx.sop.service.school.IHsSchoolInfoService#getSchoolCodeByAreaCode(java.lang.String)
	 */
	@Override
	public String getSchoolCodeByAreaCode(String areaCode) {
		String schoolNum = "";
		String maxSchoolNum = hsSchoolInfoDao.getMaxSchoolCodeByAreaCode(areaCode);
		if(StringUtils.isNotEmpty(maxSchoolNum)){
			schoolNum = (Integer.parseInt(maxSchoolNum) + 1)+"";
		}else{
			schoolNum = areaCode.substring(2)+"001";
		}
		// 如果该编码已存在继续生成，直到不存在为止
		if(hsSchoolInfoDao.checkSchoolNumber(schoolNum)>0){
			getSchoolCodeByAreaCode(areaCode);
		}
		return schoolNum;
	}
	
	public String getNextSchoolNumber(){
		String schoolNum = ""; 
		String maxSchoolNum = hsSchoolInfoDao.getMaxSchoolNumber();
		if(StringUtils.isNotEmpty(maxSchoolNum)){
			schoolNum = (Long.parseLong(maxSchoolNum)+1)+"";
		}else{
			schoolNum = "00000";
		}
		
		if(hsSchoolInfoDao.checkSchoolNumber(schoolNum)>0){
			getNextSchoolNumber();
		}
		return schoolNum;
	}
	
	@Override
	public List<BossEcinfo> findAllEcInfo() {
		return bossEcinfoDao.findAll();
	}
	
	
	@Override
	public List getSchoolNameListBySpell(String spell,List sclNameList) {
		return hsSchoolInfoDao.getSchoolNameListBySpell(spell,sclNameList);
	}
	
	@Override
	public String getMaxSchoolCodeByAreaCode2(String areaCode) {
		return hsSchoolInfoDao.getMaxSchoolCodeByAreaCode2(areaCode);
	}
	
	@Override
	public String getMaxSchoolCodeByAreaCode3(String areaCode) {
		return hsSchoolInfoDao.getMaxSchoolCodeByAreaCode3(areaCode);
	}
	
	@Override
	public String getMaxSchoolCodeByAreaCode4(String areaCode) {
		return hsSchoolInfoDao.getMaxSchoolCodeByAreaCode4(areaCode);
	}

	@Override
	public List<String> getEcIdListByBind() {
		// TODO Auto-generated method stub
		return hsSchoolInfoDao.getEcIdListByBind();
	}
	
	
	@Override
	public String getSchoolSpell(String sclName) throws Exception{
		String firstSpell = ChineseToEnglish.cn2FirstSpell(sclName);
		return setSchoolSpell(firstSpell, 0);
	} 
	
	private String setSchoolSpell(String spell,int index) throws Exception{
		int count = hsSchoolInfoDao.countSclBySpell(spell+ (index==0?"":index));
		if(count > 0){
			return setSchoolSpell(spell,(index+1));
		}else{
			return spell + (index == 0 ? "" : index);
		}
	} 
}
